package com.jcl.cloud.services.crawler.email.task;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.jcl.cloud.common.service.util.HttpClientUtil;
import com.jcl.cloud.common.service.util.PageOps;
import com.jcl.cloud.services.crawler.email.service.RedisService;
import com.jcl.cloud.services.crawler.email.util.SerializeUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.cookie.Cookie;
import org.apache.http.impl.client.BasicCookieStore;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Service
public class ZlzpCatchEmailHandler implements CatchEmailHandler {
    private final static Logger logger = LoggerFactory.getLogger(ZlzpCatchEmailHandler.class);

    @Autowired
    private RedisService redisService;

    @Override
    public void execute(String crawlerId) {

        try {
            String email = this.getEmailAddr(crawlerId);
            this.searchByEmail(crawlerId,email);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            long currentTime = System.currentTimeMillis();
            long nextExecuteTime = currentTime + 20000 ;
            this.redisService.hset("unicrawler:task:info:"+crawlerId,"nextExecuteTime",String.valueOf(nextExecuteTime));
            //释放任务
            this.redisService.lpush("unicrawler:tasks:all", crawlerId);
        }

    }







    private String getEmailAddr(String crawlerId){

        String email =   this.redisService.rpop("crawler:brain:catch-email:tasks:"+crawlerId);

        if(StringUtils.isBlank(email)){
            String url = "http://www.jucailin.com/api/user/find?ishr=1";
            String result = HttpClientUtil.doGet(url);
            logger.info("前程无忧获取到的hr和邮箱的对应关系为：" + result);
            //处理result获取email列表
            JSONObject jo = JSON.parseObject(result);
            JSONArray ja = jo.getJSONArray("users");
            for (Object object : ja) {
                JSONObject jsonob = (JSONObject) object;
                email = jsonob.getString("email");
                if(StringUtils.isNotBlank(email)){
                    this.redisService.lpush("crawler:brain:catch-email:tasks:"+crawlerId,email);
                }
            }
        }

        return email;
    }


    private void searchByEmail(String crawlerId,String email) {

        try {
            String cookieStoreStr = this.redisService.hget("unicrawler:task:info:"+crawlerId, "cookieStore");

            BasicCookieStore cookieStore = SerializeUtils.serializeToObj(cookieStoreStr);
            HttpClientContext context = HttpClientContext.create();
            context.setCookieStore(cookieStore);

            String zp_route_meta = "";


            List<Cookie> cookieList = cookieStore.getCookies();
            for (Cookie c : cookieList) {
                if (c.getName().equals("zp-route-meta")) {
                    zp_route_meta = c.getValue();
                    break;
                }
            }


            String Cookie = "";
            for (Cookie c : cookieList) {
                Cookie = Cookie + "; " + c.getName() + "=" + c.getValue();
            }
            Map<String, String> map = new HashMap<>();
            map.put("zp_route_meta", zp_route_meta);
            map.put("Cookie", Cookie.substring(1));


            if(StringUtils.isNotBlank(email)){
                map.put("email", email);
                String retResult = PageOps.getJobListByEmail(map, context);
                logger.info("智联招聘：通过email找到jobIds的返回值为：" + retResult);

                JSONArray dataList = JSON.parseObject(retResult).getJSONObject("data").getJSONArray("dataList");


                StringBuilder sb = new StringBuilder();

                for (Object o : dataList) {
                    JSONObject jObject = (JSONObject) o;
                    sb.append(",zhaopin" + jObject.getString("jobId"));
                }

                String jobIds = sb.toString();
                boolean flag = StringUtils.isNotBlank(jobIds);
                if (flag) {
                    jobIds = jobIds.substring(1);

                    //调接口入库
                    String url = "http://www.jucailin.com/api/user/setotherjobrela";
                    map = new HashMap();
                    map.put("other_jids", jobIds);
                    map.put("user_email", email);
                    logger.info(String.format("智联招聘  email = %s搜索到的对应jobIds = %s",email,jobIds));
                    String retStr = HttpClientUtil.doPostJson(url, JSON.toJSONString(map));
                    logger.info("智联招聘上传邮箱和jobId的对应关系的返回：" + retStr);
                }else {
                    logger.info(String.format("智联招聘  email = %s搜索到的对应jobIds = null",email));

                }
            }else{
                logger.info("智联招聘网站获取到的email为null,无法进行搜索");
            }
        } catch (Exception e) {
           logger.error("智联招聘   获取email和职位的对应关系发生异常:",e);
        }

    }


}
